<template>
  <div class="amap-page-container">
    <el-card shadow="never">
      <el-row :gutter="20" class="el-row-flex">
        <el-col :span="24">
          <el-row>
            <el-col :span="16">
              <el-autocomplete class="inline-input" v-model="address" :fetch-suggestions="searchMaps" placeholder="请输入内容"
                :trigger-on-focus="false" @select="positionChange">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.name }}</div>
                  <span v-if="item.address.length == 0" class="addr">{{ item.name }}</span>
                  <span v-else class="addr">{{ item.address }}</span>
                </template></el-autocomplete>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <el-amap vid="amap" :plugin="plugin" class="amap-demo" :center="centers" :zoom="zoom" :events='events'>
      <!-- 点击显示标记 -->
      <el-amap-marker v-for="(marker, index) in markers" :key="marker.index" :position="marker.position"
        :icon="marker.icon" :title="marker.title" :events="marker.events" :visible="marker.visible"
        :draggable="marker.draggable" :vid="index"></el-amap-marker>
    </el-amap>
    <div class="dis-tan ju-cen">
    </div>
  </div>
</template>

<script>
export default {
  data () {
    let self = this;
    return {
      //从这里下去是地图有关的
      address: '', //获取的位置
      zoom: 16, // 地图缩放
      centers: [
        108.911842,
        34.288263
      ], // 初始中心
      lng: 0, //经纬度
      lat: 0,
      loaded: false,
      // 点击显示的标记默认的定位
      markers: [],
      //  自动定位到当前位置
      plugin: [{
        timeout: 1000, //超过10秒后停止定位，默认：无穷大
        panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
        pName: 'Geolocation',
        events: {
          init (o) {
            // o 是高德地图定位插件实例
            o.getCurrentPosition((status, result) => {
              if (result && result.position) {
                self.address = result.formattedAddress;
                self.lng = result.position.lng;
                self.lat = result.position.lat;
                // self.centers = [self.lng, self.lat];
                // self.markers = [{
                //   position: self.centers,
                // }]
                self.loaded = true;
                self.$nextTick();
              } else {
                o.getCityInfo((status, result) => {
                  if (result && result.center) {
                    // self.address = result.formattedAddress;
                    self.lng = result.center[0];
                    self.lat = result.center[1];
                    //self.centers = result.center;
                    // self.markers = [{
                    //   position: self.centers,
                    // }]
                    self.loaded = true;
                    self.$nextTick();
                  }
                });
              }
            });
          }
        }
      }],
      // 点击地图获取当前位置并显示标记
      events: {
        click (e) {
          self.chaadd(e.lnglat)
        },
        init (o) {

          //o.setMapStyle('amap://styles/normal')
        }
      },
      addressList: [],
      position: ''
    }
  },
  created () {
    //console.log(this.address)
  },
  methods: {
    searchMap () {
      let that = this;
      let address = this.address;
      var geocoder = new AMap.Geocoder({
        city: "", //城市设为北京，默认：“全国”
      });
      geocoder.getLocation(address, function (status, result) {
        console.log("status", status)
        console.log("result", result)
        if (status === 'complete' && result.geocodes.length) {
          var lnglat = result.geocodes[0].location;
          that.centers = [lnglat.lng, lnglat.lat]
          that.lng = lnglat.lng;
          that.lat = lnglat.lat;
          that.markers = [{
            position: that.center,
          }]
          let data = {
            lng: that.lng,
            lat: that.lat
          };
          that.$emit('updateLocation', data);
        } else {
          console.log('根据地址查询位置失败');
        }
      });
    },
    searchMaps (str, cb) {
      let that = this;
      let address = this.address;
      AMap.plugin('AMap.Autocomplete', function () {
        // 实例化Autocomplete
        var autoOptions = {
          city: '全国'
        }
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(address, function (status, result) {
          cb(result.tips)
        })
      })
    },
    positionChange (e) {
      let center = [e.location.lng, e.location.lat]
      this.$emit('updateLocation', {
        lng: e.location.lng,
        lat: e.location.lat,
        address: e.district + e.address + e.name
      });
      this.centers = center
      this.markers = [{
        position: center,
      }]
    },
    chaadd (e) {
      let self = this;
      let {
        lng,
        lat
      } = e;
      self.lng = lng;
      self.lat = lat;
      self.centers = [self.lng, self.lat];
      self.loaded = true;
      self.markers = [{
        position: self.centers,
      }]
      var geocoder = new AMap.Geocoder({
        radius: 500 //范围，默认：500
      });
      var marker = new AMap.Marker();

      function regeoCode () {
        var lnglat = [lng, lat]
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            self.address = result.regeocode.formattedAddress;
            console.log(result)
            e.address = self.address
            self.$emit('updateLocation', e)
          } else {
            console.log('根据经纬度查询地址失败')
          }
        });
      }
      regeoCode();
    },
  }
}
</script>


<style lang="scss" scoped>
.amap-page-container {
  width: 800px;
  height: 600px;
}

.amap-demo {
  width: 800px;
  height: 500px;
}

.name {
  text-overflow: ellipsis;
  overflow: hidden;
}

.addr {
  font-size: 12px;
  color: #b4b4b4;
}

.inline-input {
  width: 95%;
}
</style>

<style>
/* 隐藏高德logo  */
.amap-logo {
  display: none !important;
}

.amap-geo {
  display: none !important;
}

/* 隐藏高德版权  */
.amap-copyright {
  display: none !important;
}
</style>

